1   /*
2    * Copyright (C) 2008 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect.testing.testers;
18  
19  import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
20  
21  import com.google.common.annotations.GwtCompatible;
22  import com.google.common.collect.testing.features.CollectionFeature;
23  import com.google.common.collect.testing.features.CollectionSize;
24  
25  import java.util.Collection;
26  
27  /**
28   * Tests {@link java.util.Set#hashCode}.
29   *
30   * @author George van den Driessche
31   */
32  @GwtCompatible(emulated = true)
33  public class SetHashCodeTester<E> extends AbstractSetTester<E> {
34    public void testHashCode() {
35      int expectedHashCode = 0;
36      for (E element : getSampleElements()) {
37        expectedHashCode += ((element == null) ? 0 : element.hashCode());
38      }
39      assertEquals(
40          "A Set's hashCode() should be the sum of those of its elements.",
41          expectedHashCode, getSet().hashCode());
42    }
43  
44    @CollectionSize.Require(absent = CollectionSize.ZERO)
45    @CollectionFeature.Require(ALLOWS_NULL_VALUES)
46    public void testHashCode_containingNull() {
47      Collection<E> elements = getSampleElements(getNumElements() - 1);
48      int expectedHashCode = 0;
49      for (E element : elements) {
50        expectedHashCode += ((element == null) ? 0 : element.hashCode());
51      }
52  
53      elements.add(null);
54      collection = getSubjectGenerator().create(elements.toArray());
55      assertEquals(
56          "A Set's hashCode() should be the sum of those of its elements (with "
57              + "a null element counting as having a hash of zero).",
58          expectedHashCode, getSet().hashCode());
59    }
60  }
61